package com.jysz.certificate.web.action.system;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.jysz.certificate.action.AbstractBaseAction;
import com.jysz.certificate.constant.OperCodeConstant;
import com.jysz.certificate.persistence.enums.OrganizationEnum;
import com.jysz.certificate.persistence.model.system.Organization;
import com.jysz.certificate.persistence.model.system.OrganizationDTO;
import com.jysz.certificate.persistence.model.system.Shop;
import com.jysz.certificate.service.system.OrganizationService;
import com.jysz.certificate.service.system.ShopService;
import com.jysz.webcore.ssh.annotation.PermissionPoint;
import com.jysz.webcore.utils.SshBeanUtils;

/**
 * @author <a href="mailto:javaengine@outlook.com">Kaca Rich</a>
 * 
 */
@Controller
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Namespace("/system/org")
public class OrganizationAction extends AbstractBaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private static final Logger LOG =  LoggerFactory.getLogger(OrganizationAction.class);
	
	@Resource
	private OrganizationService organizationService;
	
	private OrganizationDTO search;
	
	private Long id;
	private String userIds;
	private String shopIds;
	@Resource
	private ShopService shopService;
	
	private Organization entity;
	private Long parentId;

	@Action(INDEX)
	public String index(){
		this.setPage(organizationService.findPage(search, this.getCurrentPage(), this.getPageSize()));
		return INDEX;
	}
	
	@Action(ADD)
	@PermissionPoint(point=OperCodeConstant.SYS_ORG_ADD)
	public String add(){
		entity = new Organization();
		if(parentId != null && parentId != 0){
			entity.setParent(organizationService.find(parentId));
		}
		entity.setOrder(organizationService.getMaxOrder(parentId) + 1);
		entity.setCode(organizationService.genCode(parentId));
		return ADD;
	}
	
	
	@Action(CREATE)
	@PermissionPoint(point=OperCodeConstant.SYS_ORG_ADD)
	public String create(){
		try{
			if(entity.getType().compareTo(OrganizationEnum.ORG)==0){
				if(this.parentId != null && this.parentId > 0){
					entity.setParent(organizationService.find(parentId));
					entity.setGrade(entity.getParent().getGrade() + 1);
	//				entity.setCode(entity.getParent().getCode() + "_" + entity.getOrder());
				}else{
					entity.setGrade(1);
				}
				organizationService.save(entity);
			}else{
				OrganizationEnum type = entity.getType();
				String[] ids = null;
				String[] names = entity.getName().indexOf(",")>-1?entity.getName().split(","):new String[]{entity.getName()};
				if(entity.getType().equals(OrganizationEnum.SHOP)){
					ids = shopIds.indexOf(",")>-1?shopIds.split(","):new String[]{shopIds};
					for (int i = 0; i < ids.length; i++) {
						if(!organizationService.getPassShop(new Long(ids[i]))){
							setRedirectUrl("index.do");
							this.setSuccessPopMessage("店铺已存在，请重新选择！");
							return SHOW_MSG_PAGE;
						}
					}
				}else{
					ids = userIds.indexOf(",")>-1?userIds.split(","):new String[]{userIds};
					for (int i = 0; i < ids.length; i++) {
						if(!organizationService.getPassUser(new Long(ids[i]),parentId)){
							setRedirectUrl("index.do");
							this.setSuccessPopMessage("用户已存在，请重新选择！");
							return SHOW_MSG_PAGE;
						}
					}
				}
				entity = organizationService.find(parentId);
				
				for (int i = 0; i < ids.length; i++) {
					Organization org = new Organization();
					org.setParent(entity);
					org.setType(type);
					org.setGrade(entity.getGrade() + 1);
					org.setObjectId(new Long(ids[i]));
					org.setName(names[i]);
					org.setOrder(organizationService.getMaxOrder(parentId) + 1);
					org.setCode(organizationService.genCode(parentId));
					if(type.compareTo(OrganizationEnum.SHOP)==0){
						Shop shop = shopService.find(new Long(ids[i]));
						shop.setArea(entity);
						shopService.saveShop(shop);
					}
					organizationService.save(org);
				}
			}
			
				
				
		}catch(Exception e){
			setFailPopMessage("创建异常");
			LOG.error("创建异常", e);
		}
		
		
		setRedirectUrl("index.do");
		this.setSuccessPopMessage("创建成功");
		return SHOW_MSG_PAGE;
	}
	
	@Action(EDIT)
	@PermissionPoint(point=OperCodeConstant.SYS_ORG_EDIT)
	public String edit() {
		entity = organizationService.find(id);
		if(search != null){
			StringBuffer sb = new StringBuffer();
			sb.append("index.do?currentPage=" + getCurrentPage());
			if(StringUtils.isNotEmpty(search.getName())){
				sb.append("&search.name="+toUtf8Encode(search.getName()));
			}
			setRedirectUrl(sb.toString());
		}else{
			setRedirectUrl("index.do?currentPage=" + getCurrentPage());
		}
		if(entity == null){
			return SHOW_MSG_PAGE;
		}
		this.parentId = entity.getParent() != null ? entity.getParent().getId() : null;
		
		return EDIT;
	}
	
	@Action(UPDATE)
	@PermissionPoint(point=OperCodeConstant.SYS_ORG_EDIT)
	public String update() {
		
		try {
			    Organization organization = organizationService.find(id);
				
				String[] properties = { "name", "type", "objectId",  "order", "code" };
				SshBeanUtils.copyProperties(entity, organization, properties);
				if(parentId != null && parentId != 0){
					
					organization.setParent(organizationService.find(parentId));
				}else{
					//这是根，序号改变，会变更code，需要改变所有子菜单code
					organizationService.saveUpdateChildCode(organization);
				}
				
				organizationService.save(organization);
				setSuccessPopMessage("更新数据成功");
			// 记录日志
		} catch (Exception e) {
			setFailPopMessage("更新数据异常");
			LOG.error("更新数据异常", e);
		}
		return SHOW_MSG_PAGE;
	}
	
	@Action(DESTORY)
	@PermissionPoint(point=OperCodeConstant.SYS_ORG_DEL)
	public String destory(){
		if(organizationService.getPassOrg(id)){
			Organization org = organizationService.find(id);
			if(org.getType().compareTo(OrganizationEnum.SHOP)==0){
				if(!shopService.updateShopByOrg(org.getObjectId())){
					setRedirectUrl("index.do?currentPage="+getCurrentPage());
					setSuccessPopMessage("删除数据失败,该店铺下存在未释放或未换出的合格证");
					return SHOW_MSG_PAGE;
				}
			}
			organizationService.destory(id);
			setSuccessPopMessage("删除数据成功");
			if(search != null){
				StringBuffer sb = new StringBuffer();
				sb.append("index.do?currentPage="+getCurrentPage());
				if(StringUtils.isNotEmpty(search.getName())){
					sb.append("&search.name="+toUtf8Encode(search.getName()));
				}
				setRedirectUrl(sb.toString());
			}else{
				setRedirectUrl("index.do?currentPage="+getCurrentPage());
			}
		}else{
			setSuccessPopMessage("删除数据失败");
		}
		return SHOW_MSG_PAGE;
	}
	
	public boolean getPassOrg(Long parentId){
		return organizationService.getPassOrg(parentId);
	}
	
	public OrganizationDTO getSearch() {
		return search;
	}

	public void setSearch(OrganizationDTO search) {
		this.search = search;
	}
	
	public Organization getEntity() {
		return entity;
	}

	public void setEntity(Organization entity) {
		this.entity = entity;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long getParentId() {
		return parentId;
	}

	public void setParentId(Long parentId) {
		this.parentId = parentId;
	}

	public String getUserIds() {
		return userIds;
	}

	public void setUserIds(String userIds) {
		this.userIds = userIds;
	}

	public String getShopIds() {
		return shopIds;
	}

	public void setShopIds(String shopIds) {
		this.shopIds = shopIds;
	}
	
}
